//
//  AuctionIndexVC.swift
//  LeGou
//
//  Created by lxm on 2022/10/15.
//

import UIKit
import JXPagingView
import JXSegmentedView
class AuctionIndexVC: ZMViewController, JXSegmentedViewDelegate {
    //MARK: --------------------属性--------------------
    var cateArr = [TimeModel]()
    
    let dataSource: HomeSegDataSource = HomeSegDataSource()

    var headerInSectionHeight = 65
    
    let activities = ZMUtil.fastNilBehavior(type: [AuctionModels.Acitivity].self)
    
    var oldActivities : [AuctionModels.Acitivity]?
    
    let topInfo = ZMUtil.fastBehavior(value: Info())
    
    var needAutoLocation = true
    
    var tempHeaderView = UIView()
    
    let padding : CGFloat = 12
    
    //MARK: --------------------UI控件--------------------
    lazy var userHeaderView : AuctionHeaderView = {
        let v = ZMUtil.loadNibView(nibName: AuctionHeaderView.self)
        return v
    }()
    
    lazy var pagingView: JXPagingView = preferredPagingView()
    
    var pinView = UIView()

//    var tipsLabel = ZMUtil.label(title: "距竞购结束仅剩 01:56:12", color: "#DE3F26".zm.hex(), font: UIFont.systemFont(ofSize: 12))
    
    let orderBtn = ZMUtil.button(image: UIImage.init(named: "auction_hammer_b"))
    
    let hckBtn = ZMUtil.button(image: UIImage.init(named: "au_hck"))
    
//    let o = UIView()
    
    let seg = SegmentViewV2()
    
    let autoTips = ZMUtil.button(title: "", font: UIFont.systemFont(ofSize: 12), color: Style.mainColor).then { b in
        b.backgroundColor = UIColor.zm.color(hexString: Style.mainColorStr, 0.2)
        b.layer.cornerRadius = 4
    }
    
    var pinBottomView = UIView()
    
    // 全训按钮
    var allSelectBtn = SelectButton()
    // 一键报名
    var oneKeySignBtn = ZMUtil.button(title: "一键报名", font: UIFont.systemFont(ofSize: 12, weight: .medium), color: .white).then { b in
        b.backgroundColor = Style.mainColor
        b.layer.cornerRadius = 4
        b.contentEdgeInsets = UIEdgeInsets(top: 4, left: 12, bottom: 4, right: 12)
    }
    
    let autoList = AuctionAutoListVC()

    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        getAutoTime()
    }
    //MARK: --------------------UI--------------------
    func setUI() {
        title = "趣味竞购"
//        dataSource.itemWidth = rpx(70)
        dataSource.isItemSpacingAverageEnabled = false
        dataSource.itemSpacing = 20
        
        //配置指示器
        segmentedView.backgroundColor = .white
        segmentedView.delegate = self
//        segmentedView.isContentScrollViewClickTransitionAnimationEnabled = false
        segmentedView.dataSource = dataSource
        segmentedView.backgroundColor = .white
        segmentedView.contentEdgeInsetLeft = 22
        segmentedView.contentEdgeInsetRight = 22
        segmentedView.reloadData()
        pagingView.mainTableView.gestureDelegate = self
        pagingView.isListHorizontalScrollEnabled = false
        pagingView.backgroundColor = .clear
        pagingView.mainTableView.backgroundColor = "#F5F5F5".zm.hex()
        pagingView.mainTableView.showsVerticalScrollIndicator = false
        view.backgroundColor = "#F5F5F5".zm.hex()
        self.view.addSubview(pagingView)
        self.view.addSubview(userHeaderView)
        segmentedView.listContainer = pagingView.listContainerView
        addRefresh(scrollView: pagingView.mainTableView, addHead: true, addFoot: false) { [weak self] (refresh) in
            guard let self = self else {return}
            if self.seg.selectIndex.value == 3 {
                self.autoList.getList({ [weak self] in
                    guard let self = self else {return}
                    self.getAutoTime()
                    self.pagingView.mainTableView.mj_header?.endRefreshing()
                })
            } else {
                self.getActivity(type : self.seg.selectIndex.value)
            }
            self.loadAuctinoInfo()
        }
        self.view.addSubview(pagingView)
        
//        seg.setTitle("fuck", forSegmentAt: 0)
//        seg.setTitle("jack", forSegmentAt: 1)
        
//        let segContainer = UIView()
//        pinView.addSubview(segContainer)
//        segContainer.snp.makeConstraints { make in
//            make.top.left.right.equalToSuperview()
//            make.height.equalTo(52)
//        }
        
//        segContainer.addSubview(seg)
//        seg.snp.makeConstraints { make in
//            make.left.right.bottom.equalToSuperview()
//            make.top.equalToSuperview().offset(8)
//        }
        
        pinView.addSubview(pinBottomView)
        
        pinBottomView.snp.makeConstraints { make in
//            make.top.equalTo(segContainer.snp.bottom)
            make.top.equalToSuperview().offset(8)
            make.bottom.left.right.equalToSuperview()
        }
        
        pinBottomView.addSubview(segmentedView)
        pinBottomView.addSubview(autoTips)
        
        pinBottomView.backgroundColor = .white
        
        segmentedView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(57)
        }
        
        autoTips.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(8)
            make.right.equalToSuperview().offset(-8)
            make.height.equalTo(25)
            make.top.equalToSuperview().offset(8)
        }
        
        
        allSelectBtn.setTitle("全选", for: .normal)
        allSelectBtn.setTitleColor(UIColor.zm.color333333(), for: .normal)
        allSelectBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        pinBottomView.addSubview(allSelectBtn)
        allSelectBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(8)
            make.top.equalTo(autoTips.snp.bottom).offset(8)
        }
        
        allSelectBtn.sizeToFit()
        
        pinBottomView.addSubview(oneKeySignBtn)
        
        oneKeySignBtn.snp.makeConstraints { make in
            make.centerY.equalTo(allSelectBtn)
            make.right.equalToSuperview().offset(-8)
        }
        
        view.addSubview(orderBtn)
        
        view.addSubview(hckBtn)
        
//        setRightCustomBtn(titleStr: "竞购规则", color: UIColor.zm.color333333(), font: UIFont.systemFont(ofSize: 14, weight: .regular))
        hbd_barHidden = true
        
        hbd_barStyle = .black
        
        segStyle(s: 1)
    }
    
    func addConstraints() {
        userHeaderView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.height.equalTo(147)
            make.left.right.equalToSuperview()
        }
        
        pagingView.snp.makeConstraints { make in
            make.top.equalTo(userHeaderView.snp.bottom)
            make.bottom.equalToSuperview()
            make.right.equalToSuperview().offset(-padding)
            make.left.equalToSuperview().offset(padding)
        }
        
        orderBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-4)
            make.bottom.equalToSuperview().offset(-16)
        }
        
        hckBtn.snp.makeConstraints { make in
            make.bottom.equalTo(orderBtn.snp.top).offset(-9)
            make.right.equalToSuperview().offset(-4)
        }
    }
    
    var vcs : [ZMViewController] {
        return preferredPagingViewVC()
    }
    
    lazy var segmentedView: JXSegmentedView = JXSegmentedView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: CGFloat(headerInSectionHeight)))
    
    //MARK: --------------------methods--------------------
    func autoRefresh() {
        if DebounceTool.shard.debounce("auctionIndex_autorefresh", 2) == false {return}
        getActivity(type: seg.selectIndex.value)
        loadAuctinoInfo()
    }
        
    func segStyle(s : Int) {
        var c : UIRectCorner!
        if s == 1 {
            c = [.topRight, .topLeft]
        } else if s == 0 {
            c = [.topRight, .topLeft]
        } else {
            c = [.topRight, .topLeft]
        }
        ZMUtil.clipCircle(view: self.pinBottomView, Corner: c, radius: 16)
    }
    
    func bindAction() {
        orderBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            self.navigationController?.pushViewController(AuctionOrderIndex(), animated: true)
        }).disposed(by: disposeBag)
        
//        seg.selectIndex.skip(1).subscribe(onNext:{ [unowned self] resp in
//
//        }).disposed(by: disposeBag)
        
        seg.sholudSelect = { index, callBack in
            ZMToast.showActivity()
            self.getActivity(type: index, callBack)
            self.getAutoTime()
        }
        
        seg.selectIndex.subscribe(onNext:{ [unowned self] resp in
            self.segStyle(s:resp)
            self.segmentedView.isHidden = resp == 3
            self.autoTips.isHidden = resp != 3
            self.allSelectBtn.isHidden = resp != 3
            self.oneKeySignBtn.isHidden = resp != 3
        }).disposed(by: disposeBag)
        
        activities.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else {
//                self.o.isHidden = true
                if self.seg.selectIndex.value == 3 {
                    self.dataSource.datas = [("自动专区", "自动专区")]
                    if self.autoList.isViewLoaded {
                        self.autoList.getList()
                    }
                    self.cateArr = self.dataSource.datas.map({ a in
                        return TimeModel(cname: a.0, subTitlte: a.0, ac: AuctionModels.Acitivity())
                    })
                    self.segmentedView.reloadData()
                    self.pagingView.reloadData()
                }
                self.oldActivities = nil
                return
            }
            
            if let oldActivities = self.oldActivities {
                // 对比
                if oldActivities.count == resp.count {
                    var same = true
                    for i in 0 ..< resp.count {
                        let ac = resp[i]
                        let oAc = oldActivities[i]
                        same = (ac.id == oAc.id && ac.state == oAc.state && ac.startTime == oAc.startTime && ac.endTime == oAc.endTime)
                        if same == false {break}
                    }
                    if same {
                        // 如果一致，就走刷新当前流程
                        let index = self.segmentedView.selectedIndex
                        if oldActivities.count == 0 {
                            return
                        }
                        let ac = oldActivities[index]
                        
                        if ac.state == .over {
                            // 一致，但是当前处于的活动不是进行中，那么不需要刷新
                            return
                        }
                        if let r = self.pagingView.validListDict[index] as? AuctionListVC {
                            r.refresh()
                            return
                        }
                    }
                }
            }
            self.oldActivities = resp
            self.cateArr = resp.map({ a in
                return TimeModel(cname: AuctionService.shared.dateFromToday(.milliseconds(a.startTime)).zm.toString("HH:mm"), subTitlte: a.state.des(), ac: a)
            })
            self.dataSource.datas = self.cateArr.map({($0.cname, $0.subTitlte)})
            self.segmentedView.reloadData()
            self.pagingView.reloadData()
        }).disposed(by: disposeBag)
        
        
        topInfo.subscribe(onNext:{ [unowned self] resp in
            self.userHeaderView.today.text = resp.today.zm.toString(keep: 4)
            self.userHeaderView.month.text = resp.month.zm.toString(keep: 4)
            self.userHeaderView.total.text = resp.total.zm.toString(keep: 4)
            self.userHeaderView.canAuctionTimes.text = "\(resp.available)次"
        }).disposed(by: disposeBag)
        
        userHeaderView.profitButton.rx.tap.subscribe(onNext:{ [unowned self] resp in
            // 去收益
            let vc = VIPMallWallet()
//            vc.status = .all
//            vc.type = .auction
            self.navigationController?.pushViewController(vc, animated: true)
        }).disposed(by: disposeBag)
        
        hckBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            // 合成库
            let vc = CompoundStore()
            self.navigationController?.pushViewController(vc, animated: true)
        }).disposed(by: disposeBag)
        
        userHeaderView.ruleBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            CommonService.shared.goWeb(type: .auctionRule)
        }).disposed(by: disposeBag)
        
        autoList.allSelect.subscribe(onNext:{ [unowned self] resp in
            guard let r = resp else {
                self.allSelectBtn.isEnabled = false
                self.allSelectBtn.isSelected = false
                return
            }
            self.allSelectBtn.isSelected = r
            self.allSelectBtn.isEnabled = true
        }).disposed(by: disposeBag)
                
        self.allSelectBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            self.autoList.selectAll()
        }).disposed(by: disposeBag)
        
        oneKeySignBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
            self.autoList.oneKeySign()
        }).disposed(by: disposeBag)
    }
    
    
    
    func preferredPagingView() -> JXPagingView {
        let page = JXPagingView.init(delegate: self)
        return page
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        self.autoRefresh()
        seg.changeStyle(seg.selectIndex.value)
    }
    
    func preferredPagingViewVC() -> [ZMViewController] {
        var arr = [ZMViewController]()
        for m in cateArr {
            let vc = AuctionListVC()
            vc.activity = m.ac
            arr.append(vc)
        }
        return arr
    }
    
    // 获取活动场次列表
    func getActivity(type : Int, _ complete : ((_ flag : Bool)->())? = nil) {
        AuctionAPI.getActivities(["type":type]).rxRequestNullAble(type: [AuctionModels.Acitivity].self).subscribe(onNext:{ [unowned self] resp in
            ZMToast.hiddenActivity()
            if let complete = complete {
                complete(true)
            }
            self.headerInSectionHeight = type == 3 ? 82 : 65
            if self.seg.selectIndex.value == 3 {
                self.activities.accept(nil)
            } else {
                self.activities.accept(resp ?? [])
            }
            self.pagingView.mainTableView.mj_header?.endRefreshing()
            if self.needAutoLocation {
                self.needAutoLocation = false
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
                    guard let acs = self.activities.value else {return}
                    if let index = acs.firstIndex(where: {$0.state == .process}) {
                        self.segmentedView.selectItemAt(index: index)
                    } else if let index = acs.firstIndex(where: {$0.state == .wait}) {
                        self.segmentedView.selectItemAt(index: index)
                    }
                }
            }
        }, onError: { e in
            if let complete = complete {
                complete(false)
            }
        }).disposed(by: disposeBag)
    }
    
    func loadAuctinoInfo () {
        AuctionAPI.auctionInfo.rxRequest(type: Info.self).subscribe(onNext:{ [unowned self] resp in
            self.topInfo.accept(resp)
        }).disposed(by: disposeBag)
    }
    
    
    /// 获取自动时间
    func getAutoTime() {
        AuctionAPI.autoTime([:]).rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
            self.autoTips.setTitle(JSON(resp)["timeStr"].stringValue, for: .normal)
            let ok = JSON(resp)["timeState"].intValue != 1
            self.oneKeySignBtn.backgroundColor = ok ? Style.mainColor : "cccccc".zm.hex()
            self.oneKeySignBtn.isEnabled = ok
        }).disposed(by: disposeBag)
    }
    
    //MARK: --------------------delegate--------------------
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
    }
}

extension AuctionIndexVC : JXPagingViewDelegate {
    func pagingView(_ pagingView: JXPagingView, initListAtIndex index: Int) -> JXPagingViewListViewDelegate {
        if seg.selectIndex.value == 3 {
            return autoList
        } else {
            return vcs[index] as! JXPagingViewListViewDelegate
        }
    }
    
    func tableHeaderViewHeight(in pagingView: JXPagingView) -> Int {
//        let height = SCREEN_W / 375 * 165  + 50
//        return Int(height)
        return 0;
    }

    func tableHeaderView(in pagingView: JXPagingView) -> UIView {
        return tempHeaderView
    }

    func heightForPinSectionHeader(in pagingView: JXPagingView) -> Int {
        return headerInSectionHeight
    }

    func viewForPinSectionHeader(in pagingView: JXPagingView) -> UIView {
        return pinView
    }

    func numberOfLists(in pagingView: JXPagingView) -> Int {
        return cateArr.count
    }
}

extension AuctionIndexVC : JXPagingMainTableViewGestureDelegate {
    func mainTableViewGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        //禁止segmentedView左右滑动的时候，上下和左右都可以滚动
        if otherGestureRecognizer == segmentedView.collectionView.panGestureRecognizer {
            return false
        }
        return gestureRecognizer.isKind(of: UIPanGestureRecognizer.self) && otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.self)
    }
}

extension AuctionIndexVC {
    // MARK: - 首页列表分类
    struct TimeModel {
        var cname : String
        var subTitlte : String
        var ac : AuctionModels.Acitivity
    }
    
    // MARK: - 首页列表分类
    struct Info : HandyJSON {
        var month = 0.0
        var today = 0.0
        var total = 0.0
        var available = 0
    }
}

extension AuctionIndexVC {
    class SegmentViewV2 : LemonBaseView {
        let leftBtn = ZMUtil.button(title: "新手专区", font: UIFont.systemFont(ofSize: 14, weight: .regular), color: UIColor.zm.color999999())
        let centerBtn = ZMUtil.button(title: "普通专区", font: UIFont.systemFont(ofSize: 14, weight: .regular), color: UIColor.zm.color999999())
        let rightBtn = ZMUtil.button(title: "自动专区", font: UIFont.systemFont(ofSize: 14, weight: .regular), color: UIColor.zm.color999999())
        
        let stack = ZMUtil.stackView(axis: .horizontal).then { s in
            s.distribution = .fillEqually
        }
        
        var buttonArray = [UIButton]()
        
        let selectIndex = ZMUtil.fastBehavior(value: 3)
        
        var sholudSelect : ((_ index : Int, _ complete : @escaping ((_ ok : Bool)->()) ) -> ())?
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            setUI()
        }
        
        required init?(coder: NSCoder) {
            super.init(coder: coder)
            setUI()
        }
        
        func setUI() {
            stack.alignment = .fill
            leftBtn.tag = 1
            centerBtn.tag = 0
            rightBtn.tag = 3
            stack.addArrangedSubview(leftBtn)
            stack.addArrangedSubview(centerBtn)
            stack.addArrangedSubview(rightBtn)
            addSubview(stack)
            buttonArray.append(leftBtn)
            buttonArray.append(centerBtn)
            buttonArray.append(rightBtn)
            
            backgroundColor = .clear
            
            stack.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            
            buttonArray.forEach { b in
                b.addTarget(self, action: #selector(onClick(sender:)), for: .touchUpInside)
            }
            selectIndex.subscribe(onNext:{ [unowned self] resp in
                self.changeStyle(resp)
            }).disposed(by: disposeBag)
        }
        
        func changeStyle(_ resp : Int) {
            buttonArray.forEach { b in
                b.layer.mask = nil
                b.backgroundColor = .clear
                b.setTitleColor(UIColor.zm.color999999(), for: .normal)
            }
            
            var b : UIButton!

            if resp == 0 {
               b = self.buttonArray[1]
            } else if resp == 1 {
               b = self.buttonArray[0]
            } else {
               b = self.buttonArray[2]
            }
            ZMUtil.clipCircle(view: b, Corner: [.topLeft, .topRight], radius: 16)
            b.setTitleColor(Style.mainColor, for: .normal)
            b.backgroundColor = .white
        }
        
        @objc func onClick(sender : UIButton) {
            if let sholudSelect = sholudSelect {
                sholudSelect(sender.tag, { [weak self] ok in
                    guard let self = self else {return}
                    if ok {
                        ZMUtil.clipCircle(view: sender, Corner: [.topLeft, .topRight], radius: 16)
                        sender.setTitleColor(Style.mainColor, for: .normal)
                        sender.backgroundColor = .white
                        self.selectIndex.accept(sender.tag)
                    }
                })
            }
        }
    }
    
    class SegmentView : LemonBaseView {
        
        let leftBtn = ZMUtil.button(title: "新手专区", font: UIFont.systemFont(ofSize: 14, weight: .regular), color: UIColor.zm.color333333())
        
        let rightBtn = ZMUtil.button(title: "普通专区", font: UIFont.systemFont(ofSize: 14, weight: .regular), color: UIColor.zm.color333333())

        let selectIndex = ZMUtil.fastBehavior(value: 1)
        
        let slider = UIView().then { v in
            v.backgroundColor = .white
            v.layer.cornerRadius = 2
            v.layer.shadowColor = Style.lineColor.cgColor
            v.layer.shadowOffset = CGSize(width: 0, height: 2)
            v.layer.shadowOpacity = 1
            v.layer.shadowRadius = 4
        }
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            setUI()
        }
        
        required init?(coder: NSCoder) {
            super.init(coder: coder)
            setUI()
        }
        
        func setUI() {
            backgroundColor = "#F6F7FC".zm.hex()
            addSubview(slider)
            addSubview(leftBtn)
            addSubview(rightBtn)
            leftBtn.snp.makeConstraints { make in
                make.left.top.bottom.equalToSuperview()
                make.width.equalToSuperview().multipliedBy(0.5)
            }
            
            rightBtn.snp.makeConstraints { make in
                make.right.top.bottom.equalToSuperview()
                make.width.equalToSuperview().multipliedBy(0.5)
            }
            slider.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(2)
                make.top.equalToSuperview().offset(2)
                make.bottom.equalToSuperview().offset(-2)
                make.trailing.equalTo(leftBtn.snp.trailing).offset(-2)
            }
            
            leftBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
                if self.selectIndex.value == 1 {return}
                self.selectIndex.accept(1)
            }).disposed(by: disposeBag)
            
            rightBtn.rx.tap.subscribe(onNext:{ [unowned self] resp in
                if self.selectIndex.value == 0 {return}
                self.selectIndex.accept(0)
            }).disposed(by: disposeBag)
            
            
            selectIndex.subscribe(onNext:{ [unowned self] resp in
                if resp == 1 {
                    UIView.animate(withDuration: 0.25) {
                        self.slider.snp.remakeConstraints { make in
                            make.left.equalToSuperview().offset(2)
                            make.top.equalToSuperview().offset(2)
                            make.bottom.equalToSuperview().offset(-2)
                            make.trailing.equalTo(self.leftBtn.snp.trailing).offset(-2)
                        }
                        self.layoutIfNeeded()
                    }
                    self.leftBtn.setTitleColor(UIColor.zm.color333333(), for: .normal)
                    self.rightBtn.setTitleColor("#97A0B3".zm.hex(), for: .normal)
                } else {
                    UIView.animate(withDuration: 0.25) {
                        self.slider.snp.remakeConstraints { make in
                            make.right.equalToSuperview().offset(-2)
                            make.top.equalToSuperview().offset(2)
                            make.bottom.equalToSuperview().offset(-2)
                            make.leading.equalTo(self.rightBtn.snp.leading).offset(2)
                        }
                        self.layoutIfNeeded()
                    }
                    self.rightBtn.setTitleColor(UIColor.zm.color333333(), for: .normal)
                    self.leftBtn.setTitleColor("#97A0B3".zm.hex(), for: .normal)
                }
            }).disposed(by: disposeBag)
        }
    }
    
    
    class SelectButton : UIButton {
        override init(frame: CGRect) {
            super.init(frame: frame)
            setUI()
        }
        
        required init?(coder: NSCoder) {
            super.init(coder: coder)
            setUI()
        }
        
        func setUI() {
            setImage(UIImage.init(named: "ac_q_d"), for: .disabled)
            setImage(UIImage.init(named: "ac_q_s"), for: .selected)
            setImage(UIImage.init(named: "ac_q_u"), for: .normal)
        }
    }
}
